package com.mall.mymall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.mymall.dao.entity.Recommendations;
import com.mall.mymall.dao.entity.UserBehavior;
import com.mall.mymall.dao.entity.UserSimilarity;
import com.mall.mymall.mapper.RecommendationsMapper;
import com.mall.mymall.mapper.UserBehaviorMapper;
import com.mall.mymall.mapper.UserSimilarityMapper;
import com.mall.mymall.service.RecommendationsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 十里坡
 * @since 2025-03-14
 */
@Service
public class RecommendationsServiceImpl extends ServiceImpl<RecommendationsMapper, Recommendations> implements RecommendationsService {

    @Autowired
    private UserSimilarityMapper userSimilarityMapper;

    @Autowired
    private UserBehaviorMapper userBehaviorMapper;

    public List<Integer> getRecommendationsForUser(Integer userId, int n) {
        // 获取最相似的用户
        List<UserSimilarity> similarities = userSimilarityMapper.selectList(new QueryWrapper<UserSimilarity>()
                .or(wrapper -> wrapper.eq("user1_id", userId).or().eq("user2_id", userId)));
        Map<Integer, Double> userSimilarityMap = new HashMap<>();
        for (UserSimilarity similarity : similarities) {
            if (similarity.getUser1Id().equals(userId)) {
                userSimilarityMap.put(similarity.getUser2Id(), similarity.getSimilarityScore().doubleValue());
            } else {
                userSimilarityMap.put(similarity.getUser1Id(), similarity.getSimilarityScore().doubleValue());
            }
        }

        // 获取最相似的 n 个用户
        List<Integer> similarUsers = userSimilarityMap.entrySet().stream()
                .sorted(Map.Entry.<Integer, Double>comparingByValue().reversed())
                .limit(n)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());

        // 获取这些用户的商品行为
        List<UserBehavior> userBehaviors = userBehaviorMapper.selectList(null);
        Map<Integer, Double> itemScores = new HashMap<>();
        for (Integer similarUser : similarUsers) {
            double similarity = userSimilarityMap.get(similarUser);

            List<UserBehavior> similarUserBehaviors = userBehaviors.stream()
                    .filter(behavior -> behavior.getUserId().equals(similarUser))
                    .collect(Collectors.toList());

            for (UserBehavior behavior : similarUserBehaviors) {
                itemScores.merge(behavior.getProductId(), similarity * behavior.getBehaviorValue().doubleValue(), Double::sum);
            }
        }

        // 排序并返回推荐商品
        return itemScores.entrySet().stream()
                .sorted(Map.Entry.<Integer, Double>comparingByValue().reversed())
                .limit(n)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
    }

}
